#!/bin/bash
################################################################################
#  Copyright (C) 2025 IQIYI All rights reserved.
#
#  Author     : 王海斌
#  E-mail     : wanghaibin@qiyi.com
#  Version    :
#  Date       : Fri 18 Apr 2025 09:54:04 AM CST
#  Destription: 远端服务器列表执行命令
#              # ip_file.txt文件为每行一个ip
#              remote_exec2.sh ip ip_file.txt
#              # fuxi.txt文件为每行一个包含ip的格式化数据，需要预处理为ip文件
#              remote_exec2.sh fuxi fuxi_file.txt
#
################################################################################
cd `dirname $0`

cmd="ls -l /qke/log/ "

function run_action()
{
    local action_type=$1
    local file="$2"
    local tmp_file=./tmp_file

    if [ "$action_type" == "fuxi" ]; then
	cat $file | awk '{print $1}' | awk -F'-' '{print $NF}' >$tmp_file
        file=$tmp_file
    fi

    # 检查文件是否存在
    if [ ! -f "$file" ]; then
        echo "Error: File '$file' not found."
        exit 1
    fi
    ips=$(cat ${file})
    # 统计非空白行数
    #non_empty_lines=$(grep -c -v '^$' "${file}")
    total_lines=$(wc -l < "${file}")
    count=0
    # ssh连接超时时间
    SSH_TIMEOUT=5
    for ip in $ips
    do
        # 计数器递增
        count=$((count+1))
        ((total_lines--))
        cmd_info=`ssh -o "LogLevel=QUIET" -o ConnectTimeout=${SSH_TIMEOUT} root@"${ip}" "${cmd}"`
        cmd_stat=$?
        if [ ${cmd_stat} -ne 0 ]; then
        	echo "处理IP地址: ${ip} (cur=${count}/left=${total_lines}), SSH操作超时,stat=${cmd_stat}"
        else
        	echo "处理IP地址: ${ip} (cur=${count}/left=${total_lines})"
        	echo "${cmd_info}"
        fi
        #sleep 2
    done

    # 删除临时文件
    if [ -f $tmp_file ]; then
        rm -f $tmp_file
    fi
}



# 检测参数个数少于2或第一个参数不是ip或fuxi时直接输出用法并退出
if [[ $# -lt 2 || ( $1 != "ip" && $1 != "fuxi" ) ]]; then
    echo "Usage: $0 {ip|fuxi} <file_path>"
    echo "Example:"
    echo "        $0 ip ip_file.txt"
    echo "        $0 fuxi fuxi_file.txt"
    exit 1
fi

run_action $1 $2

echo "************** finish ********************"

